package com.study.service.impl;

import com.study.configs.RedisKeys;
import com.study.dao.QuestionDayMapper;
import com.study.pojo.entity.QuestionDay;
import com.study.pojo.resp.ResultMessage;
import com.study.service.QuestionDayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class QuestionDayServiceImpl implements QuestionDayService {

    @Autowired
    QuestionDayMapper questionDayMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResultMessage randomFive(HttpServletRequest request) {
        //通过cookie获取用户id
        Cookie[] cookie = request.getCookies();
        String userId = null;
        for (Cookie cookie2 : cookie) {
            String name = cookie2.getName();
            if ("userId".equals(name)) {
                userId = cookie2.getValue();
                break;
            }
        }
        Boolean hasKey = redisTemplate.hasKey(RedisKeys.QUESTION_DAY+userId);
        if(!hasKey){
            //从数据库查询
            List<QuestionDay> questionDays = questionDayMapper.randomFive();
            if(questionDays!=null&&questionDays.size()>0){
                //存储到redis中
                redisTemplate.opsForList().rightPushAll(RedisKeys.QUESTION_DAY+userId,questionDays);
            }else{
                redisTemplate.opsForList().rightPushAll(RedisKeys.QUESTION_DAY+userId,"");
                redisTemplate.expire(userId,60, TimeUnit.SECONDS);
            }
        }
        //从redis中获取
        List list = redisTemplate.opsForList().range(RedisKeys.QUESTION_DAY + userId, 0, -1);
        Long size = redisTemplate.opsForList().size(RedisKeys.QUESTION_DAY + userId);
        return new ResultMessage(1,"OK",list,size);
    }

}
